Page({
  data: {
    // 表单数据
    username: '',
    password: '',
    confirmPassword: '',
    
    // 密码显示状态
    showPassword: false,
    showConfirmPassword: false,
    
    // 注册状态
    isRegistering: false,
    
    // 表单验证状态
    showError: false,
    usernameValid: true,
    passwordValid: true,
    passwordMatch: true,
    formValid: false
  },
  
  // 监听输入变化
  handleInputChange(e) {
    const { name, value } = e.detail;
    this.setData({
      [name]: value
    }, () => {
      this.validateForm();
    });
  },
  
  // 切换密码显示状态
  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },
  
  // 切换确认密码显示状态
  toggleConfirmPasswordVisibility() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },
  
  // 表单验证
  validateForm() {
    const { username, password, confirmPassword } = this.data;
    
    // 验证账号
    const usernameValid = username.trim().length > 0;
    
    // 验证密码长度
    const passwordValid = password.length >= 8;
    
    // 验证密码一致性
    const passwordMatch = password === confirmPassword;
    
    // 整体表单有效性
    const formValid = usernameValid && passwordValid && passwordMatch;
    
    this.setData({
      usernameValid,
      passwordValid,
      passwordMatch,
      formValid
    });
  },
  
  // 处理注册
  async handleRegister(e) {
    this.setData({
      showError: true
    });
    
    // 再次验证表单
    this.validateForm();
    
    if (!this.data.formValid) {
      return;
    }
    
    const { username, password } = this.data;
    
    try {
      this.setData({
        isRegistering: true
      });
      
      // 模拟注册API请求
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 实际项目中这里应该调用后端注册接口
      console.log('注册成功', { username, password });
      
      // 注册成功后保存用户信息到本地存储
      wx.setStorageSync('userInfo', {
        username,
        token: 'mock-token-' + Date.now() // 模拟token
      });
      
      // 显示注册成功提示
      wx.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 1500
      });
      
      // 延迟后跳转到主页面
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index' // 假设主页面路径
        });
      }, 1500);
      
    } catch (error) {
      console.error('注册失败', error);
      wx.showToast({
        title: '注册失败，请重试',
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({
        isRegistering: false
      });
    }
  },
  
  // 跳转到登录页面
  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login' // 假设登录页面路径
    });
  },
  
  // 跳转到用户协议
  navigateToAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/agreement' // 假设用户协议页面路径
    });
  },
  
  // 跳转到隐私协议
  navigateToPrivacy() {
    wx.navigateTo({
      url: '/pages/privacy/privacy' // 假设隐私协议页面路径
    });
  }
});
    